package com.tank.dao.impl;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.tank.bean.msg.PmContent;
import com.tank.bean.msg.PmDialog;
import com.tank.bean.msg.PmTracker;
import com.tank.bean.User;
import com.tank.dao.PmDAO;

@Repository("pmDao")
public class PmDaoImpl extends TankDaoSupport implements PmDAO {


	// 发私信
	@SuppressWarnings({ "unchecked" })
	public PmContent buildDialog(PmContent pc) {

		int sid = pc.getSender().getId();
		int rid = pc.getReceiptor().getId();

		String actors = sid > rid ? rid + "," + sid : sid + "," + rid;

		List<PmDialog> pds = this.getHibernateTemplate().find(
				"from PmDialog pd where pd.actors ='" + actors + "'");

		if (pds.size() > 0) {
			pc.setDialog(pds.get(0));
		} else {

			PmDialog pd = new PmDialog();
			pd.setActors(actors);
			this.getHibernateTemplate().save(pd);
			pc.setDialog(pd);

		}

		return pc;
	}

	public PmContent buildPm(PmContent pc) {

		pc.setPubtime(new Date());
		pc.setUnread(true);
		this.getHibernateTemplate().save(pc);
		return pc;
	}

	@SuppressWarnings({ "unchecked" })
	public PmContent buildTracker(PmContent pc) {

		int pdid = pc.getDialog().getId();

		List<PmTracker> pts = this.getHibernateTemplate().find(
				"from PmTracker pt where pt.dialog.id=" + pdid);

		if (pts.size() > 1) {

			for (PmTracker pt : pts) {

				pt.setTotalCount(pt.getTotalCount() + 1);
				pt.setLastPm(pc);
				pt.setLastTime(new Date());

				if (pt.getAuthor().getId().equals(pc.getReceiptor().getId())) {// 接收者的未读信息加1
					pt.setUnreadCount(pt.getUnreadCount() + 1);

				}

				this.getHibernateTemplate().update(pt);

			}

			System.out.println("a");

		} else {
			PmTracker pt1 = new PmTracker();
			PmTracker pt2 = new PmTracker();

			// 构建发送者跟踪器
			pt1.setAuthor(pc.getSender());
			pt1.setDialog(pc.getDialog());

			pt1.setTotalCount(1);
			pt1.setUnreadCount(0);

			pt1.setLastPm(pc);
			pt1.setLastTime(new Date());

			// 构建接收者跟踪器
			pt2.setAuthor(pc.getReceiptor());
			pt2.setDialog(pc.getDialog());

			pt2.setTotalCount(1);
			pt2.setUnreadCount(1);

			pt2.setLastPm(pc);
			pt2.setLastTime(new Date());

			this.getHibernateTemplate().save(pt1);
			this.getHibernateTemplate().save(pt2);
			System.out.println("b");
		}

		return pc;
	}

	@SuppressWarnings("unchecked")
	public PmContent buildUser(PmContent pc) {
		List<User> us = this.getHibernateTemplate().find(
				"from User u where u.name ='" + pc.getReceiptor().getName().trim() + "'");
		System.out.println(us.size());
		if (us.size() > 0) {
			pc.setReceiptor(us.get(0));
		}

		return pc;
	}

	public void markRead(int actionId, int dialogId) {

		this.getHibernateTemplate()
				.bulkUpdate(
						"update PmContent pc set pc.unread = 0  where pc.receiptor.id=? and pc.dialog.id=?",
						actionId, dialogId);
		this.getHibernateTemplate()
				.bulkUpdate(
						"update PmTracker pt set pt.unreadCount = 0  where pt.author.id=? and pt.dialog.id=?",
						actionId, dialogId);

	}

	@SuppressWarnings("unchecked")
	public List<PmContent> dialog(int actionId, int dialogId) {
		List<PmContent> pcs = this
				.getHibernateTemplate()
				.find("from PmContent pc  where pc.dialog.id=? and ( pc.sender.id=? or pc.receiptor.id=? ) and (pc.remove is null or pc.remove !=?) order by pc.id desc",
						dialogId, actionId,actionId,actionId);
		return pcs;
	}

	@SuppressWarnings("unchecked")
	public List<PmTracker> trackers(Integer actionId) {
		// 如果会话消息不为空，那就找出来,按更新时间倒序
		List<PmTracker> pts = this
				.getHibernateTemplate()
				.find("from PmTracker pt join fetch pt.lastPm where pt.author.id=? and pt.totalCount>0 order by pt.lastTime desc",
						actionId);
		return pts;
	}

	public void removeBatch(int actionId, int dialogId) {
		// 标记没人删过的内容
		int a1 = this
				.getHibernateTemplate()
				.bulkUpdate(
						"update PmContent pc set pc.remove=? where pc.dialog.id=? and pc.remove is null or pc.remove =?",
						actionId, dialogId, actionId);
		// 追踪器不引用最新内容，更新其他状态
		int a2 = this
				.getHibernateTemplate()
				.bulkUpdate(
						"update PmTracker pt set pt.lastPm=null,pt.totalCount=0,pt.unreadCount = 0,lastTime=null where pt.author.id=? and pt.dialog.id=? ",
						actionId,dialogId);

		// 删除掉都要删除的
		int a3 = this.getHibernateTemplate().bulkUpdate(
				"delete PmContent  pc where  pc.dialog.id=? and pc.remove!=? and pc.remove is not null",
				dialogId, actionId);
		System.out.println(a1 + a2 - a3);
		;

	}

	public void removeContent(int actionId,int dialogId, int contentId) {
		
		//如果是删除最新那条，就要重新附上最新那条
		int removeLastPm=this
		.getHibernateTemplate()
		.bulkUpdate(
				"update PmTracker pt set pt.lastPm = null  where pt.author.id=? and pt.dialog.id=?",
				actionId, dialogId);
		
		
		System.out.println("removeLastPm"+removeLastPm);
		
		// 尝试标记
		int markMe = this
				.getHibernateTemplate()
				.bulkUpdate(
						"update PmContent pc  set pc.remove = ? where pc.id=? and pc.remove is null",
						actionId, contentId);
		
		System.out.println("actionId="+actionId+",dialogId="+dialogId+",contentId="+contentId);
		// 可以的话，删除
		int b = 0;

		System.out.println("markMe"+markMe);
		
		
		
		if (markMe == 0) {
			
			//标记不行，就只能是删除了
			b = this.getHibernateTemplate().bulkUpdate(
					"delete PmContent pc  where pc.id=?  ", contentId);
		}
		
		int updateTracker=0;
		if(removeLastPm >0){
			updateTracker=	this.getHibernateTemplate().bulkUpdate("update PmTracker pt set pt.totalCount = pt.totalCount - 1" +
					", pt.lastPm = (select max(pc.id) from PmContent pc where pc.dialog.id=? and pc.remove is null or pc.remove != ? )  " +
					"where pt.author.id=? and pt.dialog.id=?",dialogId,actionId,actionId,dialogId);
		 
		 	System.out.println("refreshLast:"+updateTracker);
		}else{
			updateTracker=	this.getHibernateTemplate().bulkUpdate("update PmTracker pt set pt.totalCount = pt.totalCount - 1" +
					"where pt.author.id=? and pt.dialog.id=? ",actionId,dialogId);
		}
		System.out.println("refreshLast:"+updateTracker);

	}

	@SuppressWarnings("unchecked")
	public Integer countUnread(Integer actionId) {
		List<Long> cs = this
				.getHibernateTemplate()
				.find("select sum(pt.unreadCount)  from PmTracker pt where pt.author.id=?",
						actionId);

		// System.out.println(cs.get(0));

		return Integer.parseInt(cs.get(0) + "");
	}

	public User dialogPartner(Integer actionId, Integer dialogId) {
		List<String> ids=this.getHibernateTemplate().find("select d.actors from PmDialog d where d.id=?",dialogId);
		System.out.println(ids.get(0));
		List<User> us=this.getHibernateTemplate().find("from User u where u.id in ("+ids.get(0)+")");
		System.out.println(us.size());
		if(us.isEmpty() || us.size()<2 ) return null;
		System.out.println(us.get(1)+"============="+us.get(0).getId());
		if(us.get(0).getId().equals(actionId)) return us.get(1);
		return us.get(0);
	}

}
